package com.example.service.impl;

import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.PurchaseRecordQueryDTO;
import com.example.entity.PurchaseRecord;
import com.example.entity.StoreProduct;
import com.example.mapper.PurchaseRecordMapper;
import com.example.mapper.StoreProductMapper;
import com.example.service.AdminPurchaseService;
import com.example.util.UserContextUtil;
import com.example.vo.PurchaseRecordVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员购买记录管理服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminPurchaseServiceImpl implements AdminPurchaseService {

    private final PurchaseRecordMapper purchaseRecordMapper;
    private final StoreProductMapper storeProductMapper;
    private final UserContextUtil userContextUtil;

    @Override
    public Result<PageResult<PurchaseRecordVO>> getPurchaseRecordsPage(PurchaseRecordQueryDTO queryDTO) {
        try {
            PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize());
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectPageWithDetails(queryDTO);
            
            // 设置购买状态显示名称
            records.forEach(record -> {
                if (record.getPurchaseStatus() != null) {
                    switch (record.getPurchaseStatus()) {
                        case 1:
                            record.setPurchaseStatusName("已完成");
                            break;
                        case 2:
                            record.setPurchaseStatusName("已取消");
                            break;
                        default:
                            record.setPurchaseStatusName("未知");
                            break;
                    }
                }
            });
            
            PageInfo<PurchaseRecordVO> pageInfo = new PageInfo<>(records);
            PageResult<PurchaseRecordVO> pageResult = new PageResult<>(
                    pageInfo.getPageNum(),
                    pageInfo.getPageSize(),
                    pageInfo.getTotal(),
                    pageInfo.getList()
            );
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询购买记录失败", e);
            return Result.error("查询购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PurchaseRecordVO>> getPurchaseRecordsByUserId(Long userId) {
        try {
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectByUserId(userId);
            
            // 设置购买状态显示名称
            records.forEach(this::setPurchaseStatusName);
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("根据用户ID查询购买记录失败，用户ID: {}", userId, e);
            return Result.error("查询购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PurchaseRecordVO>> getPurchaseRecordsByProductId(Long productId) {
        try {
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectByProductId(productId);
            
            // 设置购买状态显示名称
            records.forEach(this::setPurchaseStatusName);
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("根据商品ID查询购买记录失败，商品ID: {}", productId, e);
            return Result.error("查询购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PurchaseRecordVO>> getPurchaseRecordsByStoreManagerId(Long storeManagerId) {
        try {
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectByStoreManagerId(storeManagerId);
            
            // 设置购买状态显示名称
            records.forEach(this::setPurchaseStatusName);
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("根据店长ID查询购买记录失败，店长ID: {}", storeManagerId, e);
            return Result.error("查询购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<PurchaseRecordVO> getPurchaseRecordById(Long id) {
        try {
            PurchaseRecordVO record = purchaseRecordMapper.selectVOById(id);
            if (record == null) {
                return Result.error("购买记录不存在");
            }
            
            // 设置购买状态显示名称
            setPurchaseStatusName(record);
            
            return Result.success(record);
        } catch (Exception e) {
            log.error("根据ID查询购买记录失败，ID: {}", id, e);
            return Result.error("查询购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PurchaseRecordVO>> exportPurchaseRecords(PurchaseRecordQueryDTO queryDTO) {
        try {
            List<PurchaseRecordVO> records = purchaseRecordMapper.selectPageWithDetails(queryDTO);
            
            // 设置购买状态显示名称
            records.forEach(this::setPurchaseStatusName);
            
            return Result.success(records);
        } catch (Exception e) {
            log.error("导出购买记录失败", e);
            return Result.error("导出购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Object> getPurchaseStatistics(String startTime, String endTime) {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 构建查询条件
            PurchaseRecordQueryDTO queryDTO = new PurchaseRecordQueryDTO();
            queryDTO.setStartTime(startTime);
            queryDTO.setEndTime(endTime);
            
            // 查询所有购买记录
            List<PurchaseRecordVO> allRecords = purchaseRecordMapper.selectPageWithDetails(queryDTO);
            
            // 统计已完成的购买记录
            List<PurchaseRecordVO> completedRecords = allRecords.stream()
                    .filter(record -> record.getPurchaseStatus() != null && record.getPurchaseStatus() == 1)
                    .toList();
            
            // 统计已取消的购买记录
            List<PurchaseRecordVO> cancelledRecords = allRecords.stream()
                    .filter(record -> record.getPurchaseStatus() != null && record.getPurchaseStatus() == 2)
                    .toList();
            
            // 计算总数量和总金额
            int totalQuantity = completedRecords.stream().mapToInt(PurchaseRecordVO::getPurchaseQuantity).sum();
            BigDecimal totalAmount = completedRecords.stream()
                    .filter(record -> record.getTotalAmount() != null)
                    .map(PurchaseRecordVO::getTotalAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            statistics.put("totalRecords", allRecords.size());
            statistics.put("completedRecords", completedRecords.size());
            statistics.put("cancelledRecords", cancelledRecords.size());
            statistics.put("totalQuantity", totalQuantity);
            statistics.put("totalAmount", totalAmount);
            statistics.put("completionRate", allRecords.isEmpty() ? 0 : 
                    (double) completedRecords.size() / allRecords.size() * 100);
            
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取购买统计信息失败", e);
            return Result.error("获取购买统计信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> cancelPurchaseRecord(Long id, String reason) {
        try {
            // 查询购买记录
            PurchaseRecord record = purchaseRecordMapper.selectById(id);
            if (record == null) {
                return Result.error("购买记录不存在");
            }
            
            if (record.getPurchaseStatus() == 2) {
                return Result.error("购买记录已取消");
            }
            
            // 更新购买记录状态
            record.setPurchaseStatus(2);
            record.setRemark(record.getRemark() + (reason != null ? " [管理员取消原因: " + reason + "]" : " [管理员取消]"));
            record.setUpdateTime(LocalDateTime.now());
            
            int result = purchaseRecordMapper.updateById(record);
            if (result > 0) {
                // 如果购买记录之前是已完成状态，需要恢复商品库存
                if (record.getPurchaseStatus() == 1) {
                    StoreProduct storeProduct = storeProductMapper.selectById(record.getProductId());
                    if (storeProduct != null) {
                        int newStock = storeProduct.getCurrentStock() + record.getPurchaseQuantity();
                        storeProductMapper.updateStock(storeProduct.getId(), newStock);
                        log.info("管理员取消购买记录，恢复商品库存，商品ID: {}, 恢复数量: {}", 
                                storeProduct.getId(), record.getPurchaseQuantity());
                    }
                }
                
                log.info("管理员取消购买记录成功，记录ID: {}, 原因: {}", id, reason);
                return Result.success();
            } else {
                return Result.error("取消购买记录失败");
            }
        } catch (Exception e) {
            log.error("管理员取消购买记录失败，记录ID: {}", id, e);
            return Result.error("取消购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<Object>> getPopularProducts(int limit, String startTime, String endTime) {
        try {
            List<Map<String, Object>> popularProducts = purchaseRecordMapper.selectPopularProducts(limit, startTime, endTime);
            return Result.success(popularProducts.stream().map(item -> (Object) item).toList());
        } catch (Exception e) {
            log.error("获取热门商品购买排行失败", e);
            return Result.error("获取热门商品购买排行失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<Object>> getTopBuyers(int limit, String startTime, String endTime) {
        try {
            List<Map<String, Object>> topBuyers = purchaseRecordMapper.selectTopBuyers(limit, startTime, endTime);
            return Result.success(topBuyers.stream().map(item -> (Object) item).toList());
        } catch (Exception e) {
            log.error("获取用户购买排行失败", e);
            return Result.error("获取用户购买排行失败：" + e.getMessage());
        }
    }

    /**
     * 设置购买状态显示名称
     */
    private void setPurchaseStatusName(PurchaseRecordVO record) {
        if (record.getPurchaseStatus() != null) {
            switch (record.getPurchaseStatus()) {
                case 1:
                    record.setPurchaseStatusName("已完成");
                    break;
                case 2:
                    record.setPurchaseStatusName("已取消");
                    break;
                default:
                    record.setPurchaseStatusName("未知");
                    break;
            }
        }
    }
} 